package com.wy.classloader;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author wangyong
 */
public class CustomClassLoader extends ClassLoader {

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (name.startsWith("com.wy")) {
            return findClass(name);
        }
        return super.loadClass(name);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            if (!name.contains("com.wy")) {
                return super.findClass(name);
            }
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            String classpath = classLoader.getResource("").getPath() + name.replace(".", "/") + ".class";
            System.out.println("加载的类路径：" + classpath);
            Path filePath = Paths.get(classpath);
            byte[] classBytes = Files.readAllBytes(filePath);
            byte[] bytes = AnnotationReplacer.modifyClassBytes(classBytes);
            // 使用defineClass方法将字节码转换为Class对象
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Failed to load class: " + name, e);
        }
    }

}

